<?php
namespace app\api\controller\v1;
use app\service\OrderService;
use app\service\PaymentService;
use app\service\TechnService;
use think\Db;
use think\Request;


class Money extends Base
{
	public function _initialize()
	{
		parent::_initialize();
//		$this->IsLogin(); //验证登录
	}

	/**
	 * 用户信息
	 */
	public function index()
	{
		$user_id = $this->user['id'];
//        $user_id = 6205;
        $user_info = Db::name('user_weixin')->where('user_id',$user_id)->value('openid');
        $list = Db::name('order')
            ->alias('o')
            ->join('pay_log p','o.id = p.order_id')
            ->join('order_detail d','o.id = d.order_id')
            ->where('o.user_id',$user_id)
            ->where('o.user_is_delete_time',0)
            ->field('o.id,d.title,o.pay_price,p.*')
            ->select();
        $r_list = Db::name('order')
            ->alias('o')
            ->join('refund_log r','o.id = r.order_id')
            ->join('order_detail d','o.id = d.order_id')
            ->where('o.user_id',$user_id)
            ->where('o.user_is_delete_time',0)
            ->field('o.id,d.title,o.pay_price,r.*')
            ->select();
        foreach ($r_list as $value){
            $list[] = $value;
        }

        usort($list, 'dmp');

        foreach ($list as $kk=>$vv){
            $list[$kk]['add_time_time'] = date('Y-m-d H:i',$vv['add_time']);
            if (isset($vv['reason'])){
                $list[$kk]['name'] = '退款';
            }
        }
//        dump($list);die;
        $info['code'] = 0;
        $info['msg'] = '加载完成';
        $info['data'] = $list;
        return json_encode($info);
	}
    public function user_finishi(Request $request){
        $params = $request->param();

        $order_info = Db::name('order')->where(['id' => $params['order_id']])->find();

        $params['techn_last_address'] = Db::name('order_address')->where('order_id',$params['order_id'])->field('province,city,county,province_name,city_name,county_name,address,address_des,lng,lat')->find();
        $params['techn'] = Db::name('techn')->where('id',$order_info['techn_id'])->find();
        if (!empty($param['order_id'])){
            //判断技师实时地址
            if(empty($params['techn_last_address']))
            {
                echo json_encode(['code' => -1, 'msg' => '请授权当前地址']);
                exit();
            }
        }
        //查询订单信息
        if(empty($order_info))
        {
            echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        if($order_info['status'] != 5 && empty($params['status']))
        {
            echo json_encode(['code' => -1, 'msg' => '订单不可操作']);
            exit();
        }
        //开启事务
        Db::startTrans();
        $status=6;
        $budan_reason='';

        $upd_data = [
            'status' => $status,
            'over_time' => time(),
            'upd_time' => time(),
            'budan_reason'=>$budan_reason
        ];
        if(!Db::name('order')->where(['id' => $order_info['id']])->update($upd_data))
        {
            //事务回滚
            Db::rollback();
            echo json_encode(['code' => -1, 'msg' => '完成失败']);
            exit();
        }
        // 订单状态日志添加
        $extension_data = [
            'address' => $params['techn_last_address']
        ];
        $ordermsg='';
        if($status==9){
            $ordermsg='-补单';
        }
        $status_array = OrderService::$status_array;
        $order_status_history_id = Db::name('order_status_history')->insertGetId([
            'order_id' => $order_info['id'],
            'original_status' => $order_info['status'],
            'new_status' => $upd_data['status'],
            'msg' => '技师完成服务['.$status_array[$order_info['status']]['name'].'-'.$status_array[$upd_data['status']]['name'].']'.$ordermsg,
            'identity_type' => 'techn',
            'identity_id' => $params['techn']['id'],
            'extension_data' => json_encode($extension_data, JSON_UNESCAPED_UNICODE),
            'add_time' => time()
        ]);
        if($order_status_history_id <= 0)
        {
            Db::rollback();
            echo json_encode(['code' => -1, 'msg' => '完成失败']);
            exit();
        }
        //更新技师实时数据信息
        /*$techn_last_data = [
            'province' => $params['techn_last_address']['province'],
            'city' => $params['techn_last_address']['city'],
            'county' => $params['techn_last_address']['county'],
            'province_name' => $params['techn_last_address']['province_name'],
            'city_name' => $params['techn_last_address']['city_name'],
            'county_name' => $params['techn_last_address']['county_name'],
            'address' => $params['techn_last_address']['address'],
            'lng' => $params['techn_last_address']['lng'],
            'lat' => $params['techn_last_address']['lat'],
            'upd_time' => time()
        ];
        if(!Db::name('techn_last')->where(['techn_id' => $params['techn']['id']])->update($techn_last_data))
        {
            Db::rollback();
            echo json_encode(['code' => -1, 'msg' => '完成失败']);
            exit();
        }*/
        //处理结算信息
        $balance_list = Db::name('balance')->where(['order_id' => $order_info['id'], 'status' => 0])->select();
        if(empty($balance_list))
        {
            Db::rollback();
            echo json_encode(['code' => -1, 'msg' => '结算数据不存在']);
            exit();
        }
        $balance_ph_count = 0;
        $over_result = 0;
        foreach($balance_list as $key => $value)
        {
            switch($value['identity_type'])
            {
                //技师
                case 'techn':
                    //获取技师余额
                    $techn_info = Db::name('techn')->where(['id' => $value['identity_id']])->find();
                    if(empty($techn_info))
                    {
                        continue;
                    }
                    if ($value['balance_type'] != 2){
                        $over_result += $value['no_money'];
                    }
                    // 更新余额数据
                    $techn_money_data = [
                        'money' => Db::raw('money+'.$value['no_money']),
                        'upd_time' => time()
                    ];

                    if(!Db::name('techn')->where(['id' => $techn_info['id']])->update($techn_money_data))
                    {
                        continue;
                    }
                    //技师余额日志
                    $techn_money_log_id = Db::name('money_log')->insertGetId([
                        'identity_type' => 'techn',
                        'identity_id' => $techn_info['id'],
                        'business_type' => $value['balance_type'] == 2 ? 4 : 5,
                        'money_type' => 0,
                        'operation_type' => 1,
                        'operation_money' => $value['no_money'],
                        'original_money' => $techn_info['money'],
                        'latest_money' => $techn_info['money']+$value['no_money'],
                        'from_order_id' => $order_info['id'],
                        'msg' => '技师'.($value['balance_type'] == 2 ? '出行' : '服务').'费用',
                        'add_time' => time()
                    ]);
                    if($techn_money_log_id <= 0)
                    {
                        continue;
                    }
                    //更新当前结算信息状态
                    if(!Db::name('balance')->where(['id' => $value['id']])->update(['yes_money' => $value['no_money'], 'status' => 1, 'upd_time' => time()]))
                    {
                        continue;
                    }
                    break;
                //机构
                case 'proxy':
                    //获取机构余额
                    $proxy_info = Db::name('proxy')->where(['proxy_id' => $value['identity_id']])->find();
                    if(empty($proxy_info))
                    {
                        continue;
                    }
                    $over_result += $value['no_money'];
                    // 更新余额数据
                    $proxy_money_data = [
                        'money' => Db::raw('money+'.$value['no_money']),
                        'upd_time' => time()
                    ];

                    if(!Db::name('proxy')->where(['proxy_id' => $proxy_info['proxy_id']])->update($proxy_money_data))
                    {
                        continue;
                    }
                    //机构余额日志
                    $proxy_money_log_id = Db::name('money_log')->insertGetId([
                        'identity_type' => 'proxy',
                        'identity_id' => $proxy_info['proxy_id'],
                        'business_type' => 5,
                        'money_type' => 0,
                        'operation_type' => 1,
                        'operation_money' => $value['no_money'],
                        'original_money' => $proxy_info['money'],
                        'from_order_id' => $order_info['id'],
                        'latest_money' => $proxy_info['money']+$value['no_money'],
                        'msg' => '机构服务分成费用',
                        'add_time' => time()
                    ]);
                    if($proxy_money_log_id <= 0)
                    {
                        continue;
                    }
                    //更新当前结算信息状态
                    if(!Db::name('balance')->where(['id' => $value['id']])->update(['yes_money' => $value['no_money'], 'status' => 1, 'upd_time' => time()]))
                    {
                        continue;
                    }
                    break;
                //系统
                case 'system':
                    $over_result += $value['no_money'];

                    //更新当前结算信息状态
                    if(!Db::name('balance')->where(['id' => $value['id']])->update(['yes_money' => $value['no_money'], 'status' => 1, 'upd_time' => time()]))
                    {
                        continue;
                    }
                    break;
                //用户
                case 'user':
                    //获取用户佣金
                    $info = Db::name('user')->where(['id' => $value['identity_id']])->find();
                    if(empty($info))
                    {
                        continue;
                    }

                    $over_result += $value['no_money'];

                    if($value['khtype']==1){
                        // 更新余额数据
                        $user_money_data = [
                            'yongjin' => Db::raw('yongjin+'.$value['no_money']),
                            'upd_time' => time()
                        ];
                        if(!Db::name('user')->where(['id' => $value['identity_id']])->update($user_money_data))
                        {
                            continue;
                        }
                    }else{
                        // 更新余额数据
                        $user_money_data = [
                            'yongjin2' => Db::raw('yongjin2+'.$value['no_money']),
                            'upd_time' => time()
                        ];

                        if(!Db::name('user')->where(['id' => $value['identity_id']])->update($user_money_data))
                        {
                            continue;
                        }
                    }



                    //余额日志
                    $proxy_money_log_id = Db::name('money_log')->insertGetId([
                        'identity_type' => 'user',
                        'identity_id' => $info['id'],
                        'business_type' => 7,
                        'money_type' => 0,
                        'operation_type' => 1,
                        'operation_money' => $value['no_money'],
                        'original_money' => $info['yongjin'],
                        'from_order_id' => $order_info['id'],
                        'latest_money' => $info['yongjin']+$value['no_money'],
                        'msg' => '分佣金额',
                        'add_time' => time()
                    ]);
                    if($proxy_money_log_id <= 0)
                    {
                        continue;
                    }
                    //更新当前结算信息状态
                    if(!Db::name('balance')->where(['id' => $value['id']])->update(['yes_money' => $value['no_money'], 'status' => 1, 'upd_time' => time()]))
                    {
                        continue;
                    }
                    break;
            }
            $balance_ph_count++;
        }
        if($balance_ph_count != count($balance_list))
        {
            Db::rollback();
            echo json_encode(['code' => -100, 'msg' => '结算记录更新失败']);
            exit();
        }

        if($status==6&&!empty($params['budan_reason'])){
            db::name('order_from')->insert(['order_id'=>$params['order_id'],'title'=>$params['budan_reason'],'add_time'=>time(),'techn_id'=>$params['techn']['id']]);
        }

//        增加技师业绩
        $have_result = Db::name('techn_last')->where('techn_id',$params['techn']['id'])->field('total_result')->find();
        $now_result = $have_result['total_result']+$over_result;
        $last_re = Db::name('techn_last')->where('techn_id',$params['techn']['id'])->update(['total_result'=>$now_result]);


        TechnService::TechnPreTimey($params['techn']['id']);

        //提交事务
        Db::commit();
        echo json_encode(['code' => 0, 'msg' => '服务完成，感谢使用']);

        //走队列
        //创建任务： 项目命名空间\模块\文件夹\控制器@方法
        $job = "app\service\QueuesService@yinsi_close";
        //延时时间
        $delayed_second = 600;
        $queues_data = ['mobile' => $params['techn']['mobile']];
        \think\Queue::later($delayed_second, $job, $queues_data, 'yinsi_close');

// 		//从缓存中读取技师与客户绑定的隐私号码信息
//         $yinsi_phone = cache('yinsi_phone_'.$params['techn']['mobile']);
//         if(!empty($yinsi_phone))
//         {
//         	//解绑关系
//         	$args = [
//         		'poolKey' => 'FC100000167170034',
//         		'subsId' => $yinsi_phone['subsId'],
//         		'secretNo' => $yinsi_phone['secretNo']
//         	];
//         	\yinsi\Privacy::UnbindSubscription($args);
//         }
    }
	
}